import http from './http';
import { API_CONFIG } from '../config/api';

// 支付宝支付相关类型定义
export interface AlipayOrderRequest {
  orderNo: string;
  totalAmount: number;
  subject: string;
  body?: string;
  timeoutExpress?: string;
}

export interface AlipayOrderResponse {
  success: boolean;
  data?: {
    orderString: string;
    orderNo: string;
  };
  message?: string;
}

export interface AlipayQueryResponse {
  success: boolean;
  data?: {
    orderNo: string;
    tradeStatus: string;
    totalAmount: number;
    tradeNo?: string;
  };
  message?: string;
}

// 支付宝支付服务类
export class AlipayService {
  /**
   * 创建支付宝支付订单
   */
  static async createOrder(orderData: AlipayOrderRequest): Promise<AlipayOrderResponse> {
    try {
      const response = await http.post('/alipay/create', {
        ...orderData,
        appId: API_CONFIG.ALIPAY.APP_ID,
        notifyUrl: API_CONFIG.ALIPAY.NOTIFY_URL,
        returnUrl: API_CONFIG.ALIPAY.RETURN_URL,
      });
      
      return response;
    } catch (error) {
      console.error('创建支付宝订单失败:', error);
      return {
        success: false,
        message: '创建支付订单失败，请重试'
      };
    }
  }

  /**
   * 查询支付状态
   */
  static async queryOrder(orderNo: string): Promise<AlipayQueryResponse> {
    try {
      const response = await http.get(`/alipay/query/${orderNo}`);
      return response;
    } catch (error) {
      console.error('查询支付状态失败:', error);
      return {
        success: false,
        message: '查询支付状态失败'
      };
    }
  }

  /**
   * 发起支付宝支付（移动端）
   */
  static async pay(orderData: AlipayOrderRequest): Promise<AlipayOrderResponse> {
    try {
      // 创建支付订单
      const createResult = await this.createOrder(orderData);
      
      if (!createResult.success || !createResult.data) {
        return createResult;
      }

      // 在移动端，通常需要调用支付宝SDK
      // 这里我们模拟调用支付宝SDK的过程
      const { orderString } = createResult.data;
      
      // 检查是否在支付宝环境中
      if (typeof window !== 'undefined' && (window as any).AlipayJSBridge) {
        // 在支付宝环境中，直接调用支付
        return new Promise((resolve) => {
          (window as any).AlipayJSBridge.call('tradePay', {
            orderStr: orderString
          }, (result: any) => {
            if (result.resultCode === '9000') {
              resolve({
                success: true,
                data: createResult.data
              });
            } else {
              resolve({
                success: false,
                message: '支付失败'
              });
            }
          });
        });
      } else {
        // 不在支付宝环境中，跳转到支付宝支付页面
        const payUrl = `alipays://platformapi/startapp?appId=${API_CONFIG.ALIPAY.APP_ID}&url=${encodeURIComponent(orderString)}`;
        
        // 尝试打开支付宝APP
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = payUrl;
        document.body.appendChild(iframe);
        
        // 如果支付宝APP没有安装，跳转到网页版
        setTimeout(() => {
          document.body.removeChild(iframe);
          window.location.href = `https://openapi.alipay.com/gateway.do?${orderString}`;
        }, 2000);

        return {
          success: true,
          data: createResult.data
        };
      }
    } catch (error) {
      console.error('发起支付宝支付失败:', error);
      return {
        success: false,
        message: '发起支付失败，请重试'
      };
    }
  }

  /**
   * 处理支付回调
   */
  static handleCallback(callbackData: any): boolean {
    try {
      // 验证回调数据的签名
      console.log('收到支付宝回调:', callbackData);
      
      // 验证交易状态
      const isValidStatus = callbackData.trade_status === 'TRADE_SUCCESS' || 
                           callbackData.trade_status === 'TRADE_FINISHED';
      
      if (!isValidStatus) {
        console.log('交易状态无效:', callbackData.trade_status);
        return false;
      }
      
      // 这里可以添加更严格的签名验证逻辑
      // 使用配置的支付宝公钥验证签名
      console.log('支付回调验证通过');
      return true;
    } catch (error) {
      console.error('处理支付回调失败:', error);
      return false;
    }
  }

  /**
   * 验证支付宝签名
   */
  static verifySign(data: any, sign: string): boolean {
    try {
      // 这里应该实现真实的RSA签名验证
      // 使用配置的支付宝公钥验证签名
      console.log('验证支付宝签名:', { data, sign });
      
      // 简化版本：检查必要字段是否存在
      const requiredFields = ['trade_no', 'out_trade_no', 'trade_status', 'total_amount'];
      const hasRequiredFields = requiredFields.every(field => data[field]);
      
      return hasRequiredFields;
    } catch (error) {
      console.error('签名验证失败:', error);
      return false;
    }
  }
}

// 导出默认实例
export default AlipayService;
